package com.springboot.cloud.sysadmin.organization.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot.cloud.sysadmin.organization.dao.RoleDeptMapper;
import com.springboot.cloud.sysadmin.organization.entity.po.RoleGroup;
import com.springboot.cloud.sysadmin.organization.service.IRoleDeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created by ZengJian on 2021/2/3 0003 上午 9:22
 */
@Service
@Slf4j
public class RoleDeptService extends ServiceImpl<RoleDeptMapper, RoleGroup> implements IRoleDeptService {

    @Override
    public boolean saveBatch(String roleId, Set<String> depts) {
        if (StrUtil.isEmpty(roleId)) {
            return false;
        }
        removeByRoleId(roleId);
        Set<RoleGroup> userRoles = depts.stream().map(deptId -> new RoleGroup(roleId, deptId)).collect(Collectors.toSet());
        return saveBatch(userRoles);

    }

    @Override
    public boolean saveBatchBasic(String roleId, Set<String> depts) {
        if (ArrayUtil.isEmpty(depts)) {
            removeByRoleId(roleId);
            return false;
        }
        removeByRoleId(roleId);
        Set<RoleGroup> userRoles = depts.stream().map(deptId -> new RoleGroup(roleId, deptId)).collect(Collectors.toSet());
        return saveBatch(userRoles);
    }

    @Override
    public boolean removeByRoleId(String roleId) {
        QueryWrapper<RoleGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(RoleGroup::getRoleId, roleId);
        return remove(queryWrapper);
    }

    @Override
//    @Cached(area = "shortTime", name = "group4role::", key = "#roleId", cacheType = CacheType.BOTH)
    public Set<String> queryByRoleId(String roleId) {
        QueryWrapper<RoleGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);
        List<RoleGroup> userRoleList = list(queryWrapper);
        return userRoleList.stream().map(RoleGroup::getDeptId).collect(Collectors.toSet());
    }

    @Override
    public List<RoleGroup> queryByRoleIds(Set<String> roleIds) {
        QueryWrapper<RoleGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("role_id", roleIds);
        return this.list(queryWrapper);
    }
}
